import os
from pathlib import Path

from config import conf
from log_own import logger
from process.common_process import produce_sigle, produce_hpa
from process.t2m import produce_2t
from process.wave import produce_wave
from process.wind import produce_uv_wind, produce_10uv_wind


def get_file_list(data_dir: str, file_list=None):
    if file_list is None:
        file_list = []
    path = Path(data_dir)
    for i in path.glob("**/*.grib2"):
        file_list.append(i)
    # 文件名根据预报时间重新排序，即0h,3h,6h,12h...
    file_list = sorted(file_list, key=lambda x: int(x.stem.split("-")[1].replace("h", "")))
    return file_list


def get_var_list(dir):
    # 根据目录名获取配置文件属性值，加入列表var_list中 如：enfo oper scda等
    data_type = dir[-4:]
    var_list = conf[f"{data_type}"]
    return var_list


def process(data_dir):
    file_list = get_file_list(data_dir)

    try:
        var_list = get_var_list(data_dir)
    except Exception:
        logger.warning(data_dir + "不符合规则")
        return
    for var in var_list:
        try:
            if var == "uv":
                produce_uv_wind(file_list)
            elif var == "10uv":
                produce_10uv_wind(file_list)
            elif var == "2t":
                produce_2t(file_list)
            elif var == "wave":
                produce_wave(file_list)
            elif var == "skt" or var == "sp" or var == "msl":
                produce_sigle(file_list, var)
            elif var == "r" or var == "t":
                produce_hpa(file_list, var)
        except Exception as e:
            logger.error(var + "生产失败")
            logger.error(e)


def nc_main():
    target = ["enfo", "oper", "waef", "wave", "scda", "scwv"]
    store_grib_dir = conf["store_grib_dir"]
    for root, dirs, files in os.walk(store_grib_dir):
        for dir in dirs:
            if dir in target:
                data_dir = os.path.join(root, dir)  # ......\oper
                try:
                    process(data_dir)
                except KeyError as e:
                    logger.error(e)
                    logger.error("转换失败")


if __name__ == '__main__':
    # process("data/oper")
    # nc_main()
    # get_var_list(r"D:\hqxsoft\RD2022005-海洋大数据分析算法库研究\model-ecm_data_extraction\data\20230616000000-0h-enfo-ef-processed.grib2")
    x = get_file_list("data/oper")
    print(type(x[0]))